import { Form, Input, Modal } from "antd";
import {
    Ref,
    forwardRef,
    useImperativeHandle,
    useState,
} from "react";
import { addUser } from "../../../api/modules/user";
import { RefType } from './interface';
type ModelRef = Ref<RefType>
const ModalCom = (props: any, ref: ModelRef) => {
    const [ isModalOpen, setIsModalOpen ] = useState(false);
    const [ form ] = Form.useForm();
    const { getList } = props;
    useImperativeHandle(ref, () => {
        return {
            showModal: showModal,
        };
    });
  type FieldType = {
    username?: string;
    password?: string;
  };
  const showModal = (record: any) => {
      if (record) {
          form.setFieldsValue(record);
      } else {
          form.resetFields();
      }
      setIsModalOpen(true);
  };

  const handleOk = () => {
      form
          .validateFields()
          .then(async (valid) => {
              const id = form.getFieldValue("id");
              const params = { ...valid, id };
              const result = await addUser(params);
              setIsModalOpen(false);
              getList();
          })
          .catch((err) => {
              return false;
          });
  };

  const handleCancel = () => {
      setIsModalOpen(false);
  };

  return (
      <>
          <Modal
              title="Basic Modal"
              open={isModalOpen}
              onOk={handleOk}
              onCancel={handleCancel}
          >
              <Form
                  form={form}
                  name="basic"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  style={{ maxWidth: 600 }}
                  initialValues={{ remember: true }}
                  autoComplete="off"
              >
                  <Form.Item<FieldType>
                      label="Username"
                      name="username"
                      rules={[ { required: true, message: "Please input your username!" } ]}
                  >
                      <Input />
                  </Form.Item>

                  <Form.Item<FieldType> label="昵称" name="nickname">
                      <Input />
                  </Form.Item>
                  <Form.Item<FieldType> label="邮箱" name="email">
                      <Input />
                  </Form.Item>
                  <Form.Item<FieldType> label="密码" name="password">
                      <Input.Password />
                  </Form.Item>
                  <Form.Item<FieldType> label="地址" name="address">
                      <Input />
                  </Form.Item>
                  <Form.Item<FieldType> label="手机号码" name="phone">
                      <Input />
                  </Form.Item>
              </Form>
          </Modal>
      </>
  );
};

export default forwardRef(ModalCom);
